/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.iec.edp.caf.boot.context;

import io.iec.edp.caf.commons.utils.SpringBeanUtils;
import io.iec.edp.caf.context.core.BizContextUpdateService;
import io.iec.edp.caf.core.context.BizContext;
import lombok.Data;
import org.springframework.util.Assert;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.Optional;

/**
 * This is {@link CAFBizContextHolder}.
 *
 * @author yisiqi
 * @since 1.0.0
 */
//todo 被com.inspur.edp.bef.core.session.BefSessionManager依赖
public class CAFBizContextHolder {

    private static final ThreadLocal<BizContextThreadInfo> threadLocal = new InheritableThreadLocal<>();

    /**
     * BE已经使用了该方法，必须兼容
     *
     * @return
     * @deprecated getCurrentContext instead
     */
    @Deprecated
    public static BizContext getContext() {
        Optional<BizContext> optionalBizContext = CAFBizContextHolder.getCurrentContext();
        return optionalBizContext.orElse(null);
    }

    public static Optional<BizContext> getCurrentContext() {
        BizContextThreadInfo info = threadLocal.get();
        if (info == null)
            return Optional.empty();

        LinkedList<BizContext> bizContextStack = info.getBizContextStack();
        if (bizContextStack != null && bizContextStack.size() > 0) {
            return Optional.of(bizContextStack.peekFirst());
        }
        return Optional.empty();
    }

    public static void setCurrentContext(BizContext context) {
        Assert.notNull(context, "Only non-null BizContext instances are permitted");
        long threadId = Thread.currentThread().getId();
        BizContextThreadInfo info = threadLocal.get();
        if (info == null) {
            info = new BizContextThreadInfo();
            info.setThreadId(threadId);
            info.setBizContextStack(new LinkedList<>());
            info.getBizContextStack().push(context);
            threadLocal.set(info);
        } else {
            //判断当前线程Id与变量中的相同，如果不同，则重新构造一个对象，避免与父线程冲突
            if (info.getThreadId() != threadId) {
                BizContextThreadInfo newInfo = new BizContextThreadInfo();
                newInfo.setThreadId(threadId);
                //复制LinkedList
                newInfo.setBizContextStack(new LinkedList<>(info.getBizContextStack()));
                newInfo.getBizContextStack().push(context);
                threadLocal.set(newInfo);
            } else {
                info.getBizContextStack().push(context);
            }
        }
    }

    public static void releaseCurrentContext() {
        BizContextThreadInfo info = threadLocal.get();
        if (info == null)
            return;

        LinkedList<BizContext> bizContextStack = info.getBizContextStack();
        if (bizContextStack != null && bizContextStack.size() > 0) {
            bizContextStack.pop();
        }
    }

    public static void purge() {
        BizContextThreadInfo info = threadLocal.get();
        if (info == null)
            return;

        LinkedList<BizContext> bizContextStack = info.getBizContextStack();
        if (bizContextStack != null && bizContextStack.size() > 0) {
            BizContextUpdateService service = SpringBeanUtils.getBean(BizContextUpdateService.class);
            Iterator iterator = bizContextStack.iterator();
            while (iterator.hasNext()) {
                BizContext context = (BizContext) iterator.next();
                service.update(context);
            }
        }
        threadLocal.remove();
    }

}

@Data
class BizContextThreadInfo {
    private LinkedList<BizContext> bizContextStack;
    private long threadId;
}
